package com.elitel.frame.web.cfgsqlext.controller;

import com.elitel.common.core.domain.JsonResult;
import com.elitel.frame.web.cfgsqlext.service.CfgSqlExtService;
import com.elitel.frame.web.common.asserts.CommonAssert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;

/**
 * 脚本服务基本信息表(CfgExtsql)表控制层
 *
 * @author makejava
 * @since 2025-05-19 16:42:06
 */
@RestController
@RequestMapping("cfgSqlExt")
public class CfgSqlExtController {
    /**
     * 服务对象
     */
    @Resource
    private CfgSqlExtService cfgSqlExtService;

    @PostMapping("analyse")
    public JsonResult<?> analyse(@RequestBody Map<String, String> map) {
        String sql = map.get("sql");
        String dbKey = map.get("dbKey");
        try {
            CommonAssert.notBlank(sql, "请输入sql语句");
            CommonAssert.notBlank(dbKey, "请选择数据库");
            String decodeSql = decrypt(sql);
            Map<String, Object> analyse = cfgSqlExtService.analyse(decodeSql, dbKey);
            return JsonResult.success(analyse);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResult.error(e.getMessage());
        }

    }

    public static String decrypt(String encryptedText) throws Exception {
        String key="d3a7f4c81e6b2095f12e8d472bcf891a";
        // 截取前32字符作为IV（与JS逻辑一致）
        String ivString = key.substring(0, 16);

        // 转换密钥和IV为字节数组
        byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8);
        byte[] ivBytes = ivString.getBytes(StandardCharsets.UTF_8);

        // 处理Base64加密数据
        byte[] encryptedBytes = Base64.getDecoder().decode(encryptedText);

        // 初始化AES解密器
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

        cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);

        // 执行解密并返回UTF8字符串
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

}

